package com.study.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 实现客户端发送请求,服务器返回Hello Netty
 */
public class HelloServer {
    public static void main(String[] args) {
        //定义一对线程组
        //主线程组: 接收客户端的链接,但不做任何处理,交给从线程组处理
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //从线程组: 从主线程组接受任务,完成工作
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //创建netty服务器,启动类ServerBootstrap
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置线程组
            serverBootstrap.group(bossGroup, workerGroup) //设置主从线程组
                    .channel(NioServerSocketChannel.class)//设置nio双向通道
                    .childHandler(new HelloServerInitializer());//子处理器,用于处理workerGroup

            //启动server,并设置端口号,设置为同步方式
            ChannelFuture channelFuture = serverBootstrap.bind(8080)//设置端口号
                    .sync();
            //监听关闭的channel,设置为同步方式
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
